package com.cdel.akka.chapter2.akkademydb;

import akka.actor.AbstractActor;
import akka.actor.Status;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.pf.ReceiveBuilder;

import java.util.HashMap;
import java.util.Map;

import com.cdel.akka.chapter2.akkademydb.messages.GetRequest;
import com.cdel.akka.chapter2.akkademydb.messages.KeyNotFoundException;
import com.cdel.akka.chapter2.akkademydb.messages.SetRequest;

public class AkkademyDb extends AbstractActor {
    protected final LoggingAdapter log = Logging.getLogger(context().system(), this);
    protected final Map<String, Object> map = new HashMap<String, Object>();

    private AkkademyDb(){
        receive(ReceiveBuilder
        	//如果actor接收到一个SetRequest，就将键值存储到map中。
            .match(SetRequest.class, message -> {
                log.info("Received Set request: {}", message);
                map.put(message.key, message.value);
                sender().tell(new Status.Success(message.key), self());
            })
            //如果接收到的是GetRequest，actor就尝试从map中获取结果，如果找到key，就将value返回。如果没找到，就返回一个包含KeyNotFoundException的失败消息。
            .match(GetRequest.class, message -> {
                log.info("Received Get request: {}", message);
                Object value = map.get(message.key);
                Object response = (value != null) ? value : new Status.Failure(new KeyNotFoundException(message.key));
                sender().tell(response, self());
            })
            //接收到未知消息时，会返回一个包含了ClassNotFoundException的错误消息。
            .matchAny(o ->
            	sender().tell(new Status.Failure(new ClassNotFoundException()), self())
            )
            .build()
        );
    }
}